package shizhan.proxy;

import shizhan.pojo.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LoggingInvocationHandler implements InvocationHandler {

    private final Object target;

    public LoggingInvocationHandler(final Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            // 获取实现类中的方法信息
            Method m = target.getClass().getMethod(method.getName());
            // 判断方法上面是否有log注解
            if (m.isAnnotationPresent(Log.class)) {
                String methodName = m.getName();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime now = LocalDateTime.now();

                System.out.println("[LOG]Method: " + methodName + " started at: " + now.format(formatter));

                Object result = m.invoke(target, args);
                LocalDateTime endTime = LocalDateTime.now();
                long duration = java.time.Duration.between(now, endTime).toMillis();

                System.out.println("[LOG]Method: " + methodName + " ended at: " + endTime.format(formatter));
                System.out.println("[LOG]Method: " + methodName + " executed in: " + duration + " ms");
                return result;

            } else {
                return method.invoke(target, args);
            }


    }
}
